import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { Form, Input, Button, Radio, DatePicker, message, Card, Avatar, Tabs, Tag, Divider, Empty, Select } from 'antd';
import { UserOutlined, SettingOutlined, FileTextOutlined, HeartOutlined, GiftOutlined, PhoneOutlined, MailOutlined, LogoutOutlined } from '@ant-design/icons';
import moment from 'moment';
import MainLayout from '../../components/Layout/MainLayout';
import { User } from '../../api/types';
import { useNavigate } from 'react-router-dom';

const { TabPane } = Tabs;

const ProfileContainer = styled.div`
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px 0;
`;

const PageTitle = styled.h2`
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 30px;
  color: #333;
`;

const UserCard = styled(Card)`
  margin-bottom: 30px;
  border-radius: 8px;
  
  .ant-card-body {
    display: flex;
    align-items: center;
    position: relative;
  }
`;

const UserAvatar = styled(Avatar)`
  width: 100px;
  height: 100px;
  font-size: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
`;

const UserInfo = styled.div`
  flex: 1;
  
  .username {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 8px;
  }
  
  .info-item {
    margin-bottom: 4px;
    color: #666;
    
    .label {
      margin-right: 10px;
      display: inline-block;
      width: 80px;
      color: #999;
    }
  }
`;

const ProfileForm = styled(Form)`
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  
  .ant-form-item-label {
    width: 100px;
  }
`;

const ButtonGroup = styled.div`
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  
  button {
    margin-left: 10px;
  }
`;

const SideMenuContainer = styled.div`
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
  border: 1px solid #f0f0f0;
`;

const SideMenuItem = styled.div<{ active?: boolean }>`
  padding: 16px 20px;
  cursor: pointer;
  transition: all 0.3s;
  border-left: 3px solid ${props => props.active ? '#1890ff' : 'transparent'};
  background-color: ${props => props.active ? '#f6f6f6' : 'transparent'};
  
  &:hover {
    background-color: #f6f6f6;
  }
  
  .anticon {
    margin-right: 10px;
    color: ${props => props.active ? '#1890ff' : '#999'};
  }
`;

const OrderListContainer = styled.div`
  .order-item {
    margin-bottom: 16px;
    border-radius: 8px;
    overflow: hidden;
    border: 1px solid #f0f0f0;
  }
  
  .order-header {
    display: flex;
    justify-content: space-between;
    padding: 12px 16px;
    background-color: #f9f9f9;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .order-content {
    padding: 16px;
    display: flex;
  }
  
  .order-image {
    width: 120px;
    height: 80px;
    object-fit: cover;
    margin-right: 16px;
    border-radius: 4px;
  }
  
  .order-info {
    flex: 1;
  }
  
  .order-footer {
    display: flex;
    justify-content: flex-end;
    padding: 12px 16px;
    border-top: 1px solid #f0f0f0;
  }

  .hotel-name {
    font-weight: 500;
    font-size: 16px;
    margin-bottom: 8px;
  }

  .order-price {
    color: #ff4d4f;
    font-weight: 500;
  }
`;

// 模拟用户数据
const mockUser: User = {
  id: 'user-123456',
  username: localStorage.getItem('username') || '测试用户',
  nickname: localStorage.getItem('username') || '测试用户',
  gender: 'male',
  phone: '138****8888',
  email: 'test@example.com',
  avatar: 'https://joeschmoe.io/api/v1/random'
};

// 模拟订单数据
const mockOrders = [
  {
    id: '878456231323456135',
    hotelName: '汉庭酒店（上海虹桥机场北翟路新店）',
    address: '北翟路3386号67号',
    dateRange: '2025-03-03至2025-03-04晚/1间',
    guestName: '杨晓雯',
    roomType: '高级大床房',
    status: '已取消',
    price: '¥270',
    image: 'https://dimg04.c-ctrip.com/images/0202g120008vj5i9dB58F_R_300_225_R5_Q70_D.jpg'
  },
  {
    id: '878456231323456136',
    hotelName: '汉庭酒店（上海虹桥机场北翟路新店）',
    address: '北翟路3386号67号',
    dateRange: '2025-03-03至2025-03-04晚/1间',
    guestName: '杨晓雯',
    roomType: '高级大床房',
    status: '已取消',
    price: '¥270',
    image: 'https://dimg04.c-ctrip.com/images/0201f120008vj5fso7B72_R_300_225_R5_Q70_D.jpg'
  },
  {
    id: '878456231323456137',
    hotelName: '汉庭酒店（上海虹桥机场北翟路新店）',
    address: '北翟路3386号67号',
    dateRange: '2025-03-03至2025-03-04晚/1间',
    guestName: '杨晓雯',
    roomType: '高级大床房',
    status: '已取消',
    price: '¥270',
    image: 'https://dimg04.c-ctrip.com/images/02037120008vj5hl34922_R_300_225_R5_Q70_D.jpg'
  }
];

// 模拟常用联系人数据
const mockContacts = [
  { id: 1, name: '丁淼', email: '--', phone: '13192489713' },
  { id: 2, name: '蒙汝鑫', email: 'dmlcjxsqqx5@live.com', phone: '13192489713' },
  { id: 3, name: '金子圆', email: '--', phone: '13192489713' },
  { id: 4, name: '邱狮鹏', email: 'srgwt5rz28@0355.net', phone: '13192489713' },
  { id: 5, name: '王易轩', email: '--', phone: '13192489713' },
  { id: 6, name: '成玥傲', email: '--', phone: '13192489713' }
];

// 模拟优惠券数据
const mockCoupons = [
  { id: 1, title: '国内部分酒店满减券', value: 20, minAmount: 200, expireDate: '2025.10.10', status: 'valid' },
  { id: 2, title: '国内部分酒店满减券', value: 20, minAmount: 200, expireDate: '2025.10.10', status: 'valid' },
  { id: 3, title: '国内部分酒店满减券', value: 20, minAmount: 200, expireDate: '2025.10.10', status: 'valid' },
  { id: 4, title: '国内部分酒店满减券', value: 20, minAmount: 200, expireDate: '2025.10.10', status: 'valid' },
  { id: 5, title: '国内部分酒店满减券', value: 20, minAmount: 200, expireDate: '2025.10.10', status: 'valid' },
  { id: 6, title: '国内部分酒店满减券', value: 20, minAmount: 200, expireDate: '2025.10.10', status: 'valid' }
];

const ProfilePage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [user, setUser] = useState<User>(mockUser);
  const navigate = useNavigate();
  const [activeSection, setActiveSection] = useState('profile');
  
  useEffect(() => {
    // 模拟从后端获取用户数据
    setUser(mockUser);
    
    // 设置表单初始值
    form.setFieldsValue({
      username: mockUser.username,
      nickname: mockUser.nickname || '',
      gender: mockUser.gender || 'male',
      phone: mockUser.phone,
      email: mockUser.email || '',
      birthday: mockUser.birthday ? moment(mockUser.birthday) : null
    });
  }, [form]);
  
  const handleSave = async (values: any) => {
    setLoading(true);
    
    // 模拟保存用户信息
    setTimeout(() => {
      const updatedUser = {
        ...user,
        ...values,
        birthday: values.birthday ? values.birthday.format('YYYY-MM-DD') : undefined
      };
      
      setUser(updatedUser);
      message.success('保存成功');
      setLoading(false);
    }, 800);
  };
  
  const handleReset = () => {
    form.setFieldsValue({
      username: user.username,
      nickname: user.nickname || '',
      gender: user.gender || 'male',
      phone: user.phone,
      email: user.email || '',
      birthday: user.birthday ? moment(user.birthday) : null
    });
  };
  
  const handleLogout = () => {
    // 清除登录信息
    localStorage.removeItem('token');
    localStorage.removeItem('username');
    message.success('退出登录成功');
    navigate('/login');
  };

  const renderSideMenu = () => (
    <SideMenuContainer>
      <SideMenuItem active={activeSection === 'orders'} onClick={() => setActiveSection('orders')}>
        <FileTextOutlined /> 订单管理
      </SideMenuItem>
      <SideMenuItem active={activeSection === 'coupons'} onClick={() => setActiveSection('coupons')}>
        <GiftOutlined /> 优惠券
      </SideMenuItem>
      <SideMenuItem active={activeSection === 'contacts'} onClick={() => setActiveSection('contacts')}>
        <UserOutlined /> 常用信息
      </SideMenuItem>
      <SideMenuItem active={activeSection === 'favorites'} onClick={() => setActiveSection('favorites')}>
        <HeartOutlined /> 我的收藏
      </SideMenuItem>
      <SideMenuItem active={activeSection === 'profile'} onClick={() => setActiveSection('profile')}>
        <SettingOutlined /> 个人信息
      </SideMenuItem>
    </SideMenuContainer>
  );

  const renderOrders = () => (
    <OrderListContainer>
      <PageTitle>订单管理</PageTitle>
      <Tabs defaultActiveKey="all">
        <TabPane tab="全部订单" key="all">
          {mockOrders.map(order => (
            <div className="order-item" key={order.id}>
              <div className="order-header">
                <div>订单号: {order.id}</div>
                <Tag color="default">{order.status}</Tag>
              </div>
              <div className="order-content">
                <img src={order.image} alt={order.hotelName} className="order-image" />
                <div className="order-info">
                  <div className="hotel-name">{order.hotelName}</div>
                  <div>{order.address}</div>
                  <div>入住日期: {order.dateRange}</div>
                  <div>入住人: {order.guestName}</div>
                  <div>{order.roomType}</div>
                </div>
                <div className="order-price">
                  在线付 {order.price}
                </div>
              </div>
              <div className="order-footer">
                <Button type="default" style={{ marginRight: 8 }}>酒店详情</Button>
                <Button type="primary">再次预定</Button>
              </div>
            </div>
          ))}
        </TabPane>
        <TabPane tab="未出行" key="upcoming">
          <Empty description="暂无未出行订单" />
        </TabPane>
        <TabPane tab="待支付" key="payment">
          <Empty description="暂无待支付订单" />
        </TabPane>
        <TabPane tab="待点评" key="review">
          <Empty description="暂无待点评订单" />
        </TabPane>
      </Tabs>
    </OrderListContainer>
  );

  const renderContacts = () => (
    <div>
      <PageTitle>常用信息</PageTitle>
      <Button type="primary" style={{ marginBottom: 16 }}>+ 新增常用信息</Button>
      <Card>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ borderBottom: '1px solid #f0f0f0' }}>
              <th style={{ padding: '12px 20px', textAlign: 'left' }}>姓名</th>
              <th style={{ padding: '12px 20px', textAlign: 'left' }}>邮箱</th>
              <th style={{ padding: '12px 20px', textAlign: 'left' }}>联系电话</th>
              <th style={{ padding: '12px 20px', textAlign: 'center' }}>操作</th>
            </tr>
          </thead>
          <tbody>
            {mockContacts.map(contact => (
              <tr key={contact.id} style={{ borderBottom: '1px solid #f0f0f0' }}>
                <td style={{ padding: '12px 20px' }}>{contact.name}</td>
                <td style={{ padding: '12px 20px' }}>{contact.email}</td>
                <td style={{ padding: '12px 20px' }}>{contact.phone}</td>
                <td style={{ padding: '12px 20px', textAlign: 'center' }}>
                  <Button type="link" danger>删除</Button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );

  const renderCoupons = () => (
    <div>
      <PageTitle>优惠券</PageTitle>
      <Tabs defaultActiveKey="unused">
        <TabPane tab="未使用" key="unused">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: '16px' }}>
            {mockCoupons.map((coupon, index) => (
              <div key={coupon.id} style={{ 
                width: 'calc(50% - 8px)',
                background: index < 2 ? '#fff2f0' : '#f5f5f5',
                borderRadius: '8px',
                overflow: 'hidden',
                display: 'flex',
                marginBottom: '16px'
              }}>
                <div style={{ 
                  width: '120px', 
                  background: index < 2 ? '#ff4d4f' : '#bfbfbf',
                  color: 'white',
                  display: 'flex',
                  flexDirection: 'column',
                  justifyContent: 'center',
                  alignItems: 'center',
                  padding: '20px 0'
                }}>
                  <div style={{ fontSize: '24px', fontWeight: 'bold' }}>¥{coupon.value}</div>
                  <div>无门槛</div>
                </div>
                <div style={{ flex: 1, padding: '16px' }}>
                  <div style={{ fontSize: '16px', marginBottom: '8px' }}>{coupon.title}</div>
                  <div style={{ color: '#999', fontSize: '12px', marginBottom: '8px' }}>有效期至 {coupon.expireDate}</div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '16px' }}>
                    <a href="#" style={{ color: '#999', fontSize: '12px' }}>使用说明 &gt;</a>
                    <Button type="primary" size="small" disabled={index >= 2}>
                      去使用
                    </Button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </TabPane>
        <TabPane tab="已使用" key="used">
          <Empty description="暂无已使用的优惠券" />
        </TabPane>
        <TabPane tab="已过期" key="expired">
          <Empty description="暂无已过期的优惠券" />
        </TabPane>
        <TabPane tab="待点评" key="review">
          <Empty description="暂无待点评的优惠券" />
        </TabPane>
      </Tabs>
    </div>
  );

  const renderFavorites = () => (
    <div>
      <PageTitle>我的收藏</PageTitle>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: '20px' }}>
        {[1, 2, 3, 4, 5, 6, 7, 8].map(id => (
          <Card
            key={id}
            hoverable
            style={{ width: 'calc(25% - 15px)', marginBottom: '20px' }}
            cover={<img alt="酒店图片" src={`https://dimg04.c-ctrip.com/images/02037120008vj5hl3492${id}_R_300_225_R5_Q70_D.jpg`} style={{ height: '160px', objectFit: 'cover' }} />}
          >
            <Card.Meta
              title="上海新国际博览中心城际酒店"
              description="5.0 超棒"
            />
            <div style={{ marginTop: '10px', color: '#ff4d4f', fontWeight: 'bold' }}>¥683</div>
          </Card>
        ))}
      </div>
    </div>
  );

  const renderUserInfo = () => (
    <div>
      <PageTitle>个人信息</PageTitle>
      <Card style={{ marginBottom: '30px' }}>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Avatar size={100} src={user.avatar} icon={<UserOutlined />} />
          <div style={{ marginLeft: '20px' }}>
            <div style={{ fontWeight: 'bold', fontSize: '18px', marginBottom: '8px' }}>
              {user.nickname}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
              <PhoneOutlined style={{ marginRight: '8px', color: '#999' }} />
              {user.phone}
            </div>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <MailOutlined style={{ marginRight: '8px', color: '#999' }} />
              {user.email}
            </div>
          </div>
        </div>
      </Card>

      <Card title="基本信息">
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
          initialValues={{
            gender: 'female',
          }}
        >
          <Form.Item label="昵称" name="nickname">
            <Input placeholder="这里是我的网名" />
          </Form.Item>
          
          <Form.Item label="性别" name="gender">
            <Radio.Group>
              <Radio value="female">女</Radio>
              <Radio value="male">男</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="生日" style={{ display: 'flex' }}>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Select defaultValue="2001" style={{ width: 100, marginRight: 8 }}>
                {Array.from({ length: 50 }, (_, i) => 2023 - i).map(year => (
                  <Select.Option key={year} value={year}>{year}年</Select.Option>
                ))}
              </Select>
              <Select defaultValue="12" style={{ width: 80, marginRight: 8 }}>
                {Array.from({ length: 12 }, (_, i) => i + 1).map(month => (
                  <Select.Option key={month} value={month}>{month}月</Select.Option>
                ))}
              </Select>
              <Select defaultValue="11" style={{ width: 80 }}>
                {Array.from({ length: 31 }, (_, i) => i + 1).map(day => (
                  <Select.Option key={day} value={day}>{day}日</Select.Option>
                ))}
              </Select>
            </div>
          </Form.Item>

          <Form.Item label="手机" name="phone">
            <Input placeholder="18920551322" />
          </Form.Item>

          <Divider />
          
          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading}>
              保存
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );

  const renderContent = () => {
    switch(activeSection) {
      case 'orders':
        return renderOrders();
      case 'coupons':
        return renderCoupons();
      case 'contacts':
        return renderContacts();
      case 'favorites':
        return renderFavorites();
      case 'profile':
      default:
        return renderUserInfo();
    }
  };
  
  return (
    <MainLayout>
      <ProfileContainer>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '20px', alignItems: 'center' }}>
          <h1 style={{ margin: 0, fontSize: '24px' }}>个人中心</h1>
          <Button onClick={handleLogout} icon={<LogoutOutlined />}>退出登录</Button>
        </div>

        <div style={{ display: 'flex', gap: '20px' }}>
          <div style={{ width: '200px' }}>
            {renderSideMenu()}
          </div>
          <div style={{ flex: 1 }}>
            {renderContent()}
          </div>
        </div>
      </ProfileContainer>
    </MainLayout>
  );
};

export default ProfilePage; 